<template>
	<view>
		<!-- #ifndef MP-WEIXIN -->
		<uni-nav-bar :title="title" :fixed="true" :border="false" :status-bar="true" @clickLeft="$tab.back(0)"
			@clickRight="rightClick">
			<block slot="left">
				<view class="flex items-center">
					<u-icon name="arrow-left" :bold="true" size="40rpx" color="#000"></u-icon>
					<view class="text-nowrap" v-if="againSocketTimer">
						重连中...
					</view>
				</view>
			</block>
			<block slot="right" v-if="title != '在线客服'">
				<u-icon name="more-dot-fill" color="#000" :bold="true"></u-icon>
			</block>
		</uni-nav-bar>
		<!-- #endif -->

		<!-- #ifdef MP-WEIXIN -->
		<uni-nav-bar :fixed="true" :border="false" :status-bar="true" left-width="500rpx">
			<block slot="left">
				<view class="flex items-center">
					<u-icon name="arrow-left" color="#000" size="40rpx" :bold="true" @click="handleBack"></u-icon>
					<view class="font-500 text-32 ml-16 text-nowrap" style="padding-bottom: 8rpx;width: 450rpx;"
						@click="rightClick">
						{{title}}
					</view>
				</view>
			</block>
		</uni-nav-bar>
		<!-- #endif -->

		<view class="content" @touchstart="hideDrawer(true)">
			<scroll-view class="msg-list" :scroll-y="true" :scroll-with-animation="scrollAnimation"
				:scroll-into-view="scrollToView" @scrolltoupper="loadHistory" upper-threshold="20" @scroll="msgScroll">
				<!-- 加载历史数据waitingUI -->
				<view class="loading" v-if="loading">
					<view class="spinner">
						<view class="rect1"></view>
						<view class="rect2"></view>
						<view class="rect3"></view>
						<view class="rect4"></view>
						<view class="rect5"></view>
					</view>
				</view>
				<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.id" @click="closePop">
					<!-- 系统消息 -->
					<block v-if="row.msgType == 0">
						<view class="system">
							<!-- 文字消息  系统时间-->
							<view v-if="row.msgContentType=='text' || row.msgContentType=='sysTime'" class="text">
								{{row.content}}
							</view>
							<!-- 领取红包消息 -->
							<view v-if="row.msgContentType=='redEnvelope'" class="red-envelope">
								<image src="/static/img/red-envelope-chat.png"></image>
								{{row.content.text}}
							</view>
							<!-- 消息撤回 重新编辑 -->
							<view v-if="row.msgContentType=='msg_reback'" class="text">
								<view class="" style="padding: 0;">
									{{row.sendUserInfo.userId == userInfo.userId ? '你' : row.sendUserInfo.nickName}}撤回了一条消息
								</view>
								<view class="ml-16" style="padding: 0;color: #4798f8;" @click="handleReEdit(row)"
									v-if="row.rebackMsgContentType && row.rebackMsgContentType == 'text' && row.sendUserInfo.userId == userInfo.userId">
									重新编辑
								</view>
							</view>
						</view>
					</block>
					<!-- 用户消息 -->
					<block v-if="row.msgType == 1">
						<!-- 自己发出的消息 -->
						<view class="my" v-if="row.senderId == userInfo.userId">
							<!-- 左-消息 -->
							<view class="left">
								<view class="text-popup flex items-center px-48 flex-wrap" v-if="row.select">
									<view class="flex flex-col items-center mr-48 " @click.stop="handleCopy"
										v-if="row.msgContentType=='text'">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_copy.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											复制
										</view>
									</view>
									<view class="flex flex-col items-center mr-48" @click.stop="handleDelete">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_del.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											删除
										</view>
									</view>
									<view class="flex flex-col items-center mr-48" @click.stop="handleWithdraw"
										v-if="withdraw">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_back.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											撤回
										</view>
									</view>
									<view class="flex flex-col items-center mr-48" @click.stop="handleForward">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/forward.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											转发
										</view>
									</view>
									<!-- #ifdef APP -->
									<view class="flex flex-col items-center" @click.stop="uniShare(row)"
										v-if="row.msgContentType=='text' || row.msgContentType=='img'">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon-share.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											分享
										</view>
									</view>
									<!-- #endif -->

								</view>

								<!-- 文字消息 -->
								<view class="w-full flex items-center"
									v-if="row.msgContentType=='text' || row.msgContentType=='atText'"
									@longpress="handlePopup(row)" style="justify-content: flex-end;">
									<u-icon name="info-circle-fill" color="#E74033" class="mr-20"
										v-if="row && row.socket == 0" @click="retransmission(row)"></u-icon>
									<view class="bubble text-FFF rich-text" style="background: #37ACA4;">
										<view class="sanjiao" v-if="row.select">

										</view>
										<mp-html :content="row.content.text" style="font-size: 40rpx;" />
									</view>
								</view>

								<!-- 接龙 -->
								<view class="w-full flex flex-col" v-if="row.msgContentType=='jielong'"
									@longpress="handlePopup(row)" style="align-items: flex-end;">
									<view class="bubble text-FFF rich-text" style="background: #37ACA4;">
										<view class="sanjiao" v-if="row.select">

										</view>
										<mp-html :content="row.content" style="font-size: 36rpx;" />
									</view>

									<view class="mt-16" style="max-width: 80%;"
										@click="$tab.nav(`/pages/chat2/jielong?groupId=${groupId}&msgId=${row.id}`)">
										<view class="jielong flex items-center bg-FFF">
											<view class="text-20">
												参与接龙
											</view>
											<u-icon name="arrow-right" size="12px" color="#333"></u-icon>
										</view>
									</view>
								</view>

								<!-- 语言消息 -->
								<view v-if="row.msgContentType=='voice'" class="bubble voice text-FFF" style="background: #37ACA4;"
									@tap="playVoice(row)" :class="playMsgid == row.id?'play':''"
									@longpress="handlePopup(row)">
									<view class="sanjiao" v-if="row.select">

									</view>
									<view class="length">{{row.content.length}}</view>
									<view class="icon my-voice"></view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msgContentType=='img'" class="bubble img" @tap="showPic(row)"
									@longpress="handlePopup(row)">
									<view class="sanjiao" v-if="row.select">

									</view>
									<image :src="row.content.url"
										:style="{'width': row.content.w+'px','height': row.content.h+'px'}">
									</image>
								</view>
								<!-- 视频消息 -->
								<view v-if="row.msgContentType=='video'" class="bubble img"
									@tap="showVideo(row.content.url)">
									<view class="relative">
										<image :src="row.content.poster"
											:style="{'width': row.content.w+'px','height': row.content.h+'px'}"
											@longpress="handlePopup(row)">
										</image>
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_bofang@3x.png"
											class="play-btn" mode=""></image>
										<view class="duration">
											{{row.content.duration}}
										</view>
									</view>
									<view class="sanjiao" v-if="row.select">

									</view>
								</view>
								<!-- 红包 -->
								<view v-if="row.msgContentType=='red_packet'" class="bubble red-envelope"
									@tap="openRedEnvelope(row)">
									<image src="/static/img/red-envelope.png"></image>
									<view class="tis">
										<!-- 点击开红包 -->
									</view>
									<view class="blessing">
										{{row.content.remark}}
									</view>
								</view>
								<!-- 文件 -->
								<view v-if="row.msgContentType=='file'" class="bubble file-box"
									@click="openFile(row.content)" @longpress="handlePopup(row)">
									<view class="" style="width: 300rpx;">
										<view class="u-line-1" style="color: #000;">
											{{row.content.name}}
										</view>
										<view class="mt-20 u-line-1 text-24" style="color: #c8c8c8;">
											{{row.content.size}}
										</view>
									</view>
									<u-icon name="file-text-fill" :bold="true" color="#8b572a" size="40px"></u-icon>
								</view>
							</view>
							<!-- 右-头像 -->
							<view class="right">
								<image :src="row.sendUserInfo.avatar"
									@click="$tab.nav(`/pages/mine/setting/userModify`)"></image>
							</view>
						</view>
						<!-- 别人发出的消息 -->
						<view class="other" v-if="row.senderId != userInfo.userId">
							<!-- 左-头像 -->
							<view class="left">
								<image :src="row.sendUserInfo.avatar" @click="hendClick(row)"></image>
							</view>
							<!-- 右-用户名称-时间-消息 -->
							<view class="right" style="display: block;">
								<view class="text-popup flex items-center px-48 " v-if="row.select">
									<view class="flex flex-col items-center mr-48" @click.stop="handleCopy"
										v-if="row.msgContentType=='text'">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_copy.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											复制
										</view>
									</view>
									<view class="flex flex-col items-center mr-48" @click.stop="handleDelete">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_del.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											删除
										</view>
									</view>
									<view class="flex flex-col items-center mr-48" @click.stop="handleWithdraw"
										v-if="withdraw">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_back.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											撤回
										</view>
									</view>
									<view class="flex flex-col items-center mr-48" @click.stop="handleForward">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/forward.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											转发
										</view>
									</view>
									<!-- #ifdef APP -->
									<view class="flex flex-col items-center" @click.stop="uniShare(row)"
										v-if="row.msgContentType=='text' || row.msgContentType=='img'">
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon-share.png"
											class="image-48" mode=""></image>
										<view class="text-FFF mt-16">
											分享
										</view>
									</view>
									<!-- #endif -->
								</view>

								<view class="mb-12">
									{{row.sendUserInfo.nickName}}
								</view>

								<!-- 文字消息 -->
								<view v-if="row.msgContentType=='text' || row.msgContentType=='atText'"
									class="bubble bg-white text-333 rich-text" @longpress="handlePopup(row)"
									style="display: inline-block;">
									<mp-html :content="row.content.text" style="font-size: 36rpx;" />
									<view class="sanjiao" v-if="row.select">

									</view>
								</view>

								<!-- 接龙 -->
								<view class="w-full flex flex-col" v-if="row.msgContentType=='jielong'"
									@longpress="handlePopup(row)" style="align-items: start;">
									<view class="bubble text-FFF rich-text" style="background: #37ACA4;">
										<view class="sanjiao" v-if="row.select">

										</view>
										<mp-html :content="row.content" style="font-size: 36rpx;" />
									</view>

									<view class="mt-16" style="max-width: 80%;"
										@click="$tab.nav(`/pages/chat2/jielong?groupId=${groupId}&msgId=${row.id}`)">
										<view class="jielong flex items-center bg-FFF">
											<view class="text-20">
												参与接龙
											</view>
											<u-icon name="arrow-right" size="12px" color="#333"></u-icon>
										</view>
									</view>
								</view>

								<!-- 语音消息 -->
								<view v-if="row.msgContentType=='voice'" class="bubble voice bg-white text-333"
									@tap="playVoice(row)" :class="playMsgid == row.id?'play':''"
									@longpress="handlePopup(row)">
									<view class="icon other-voice"></view>
									<view class="length">{{row.content.length}}</view>
									<view class="sanjiao" v-if="row.select">

									</view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msgContentType=='img'" class="bubble img" @tap="showPic(row)">
									<image :src="row.content.url"
										:style="{'width': row.content.w+'px','height': row.content.h+'px'}"
										@longpress="handlePopup(row)">
									</image>
									<view class="sanjiao" v-if="row.select">

									</view>
								</view>
								<!-- 视频消息 -->
								<view v-if="row.msgContentType=='video'" class="bubble img"
									@tap="showVideo(row.content.url)">
									<view class="relative">
										<image :src="row.content.poster"
											:style="{'width': row.content.w+'px','height': row.content.h+'px'}"
											@longpress="handlePopup(row)">
										</image>
										<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_bofang@3x.png"
											class="play-btn" mode=""></image>
										<view class="duration">
											{{row.content.duration}}
										</view>
									</view>
									<view class="sanjiao" v-if="row.select">

									</view>
								</view>
								<!-- 红包 -->
								<view v-if="row.msgContentType=='red_packet'" class="bubble red-envelope"
									@tap="openRedEnvelope(row)" style="justify-content: space-between;">
									<image src="/static/img/red-envelope.png"></image>
									<view class="tis">
										<!-- 点击开红包 -->
									</view>
									<view class="blessing">
										{{row.content.remark}}
									</view>
								</view>
								<!-- 文件 -->
								<view v-if="row.msgContentType=='file'" class="bubble file-box"
									@click="openFile(row.content)" @longpress="handlePopup(row)">
									<view class="" style="width: 300rpx;">
										<view class="u-line-1" style="color: #000;">
											{{row.content.name}}
										</view>
										<view class="mt-20 u-line-1 text-24" style="color: #c8c8c8;">
											{{row.content.size}}
										</view>
									</view>
									<u-icon name="file-text-fill" :bold="true" color="#8b572a" size="40px"></u-icon>
								</view>
							</view>
						</view>
					</block>
				</view>
			</scroll-view>
		</view>
		<!-- 抽屉栏 -->
		<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 表情 -->
			<swiper class="emoji-swiper" :class="{hidden:hideEmoji}" indicator-dots="true" duration="150">
				<swiper-item v-for="(page,pid) in emojiList" :key="pid">
					<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
						<image mode="widthFix" :src="'http://api.fceos.cn/qiliaoyun/profile/appImages/emoji/' + em.url">
						</image>
					</view>
				</swiper-item>
			</swiper>
			<!-- 更多功能 相册-拍照-红包 -->
			<view class="more-layer" :class="{hidden:hideMore}">
				<view class="list">
					<view class="box" @tap="chooseImage(false)">
						<view class="icon tupian2"></view>
					</view>
					<view class="box" @tap="camera(false)">
						<view class="icon paizhao"></view>
					</view>
					<view class="box" @tap="handRedEnvelopes">
						<view class="icon hongbao"></view>
					</view>
					<view class="box" @tap="handleChooseFile(false)">
						<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/file.png" style="width:94rpx;"
							mode="widthFix"></image>
					</view>
					<view class="box" @tap="$tab.nav(`/pages/chat2/jielong?groupId=${groupId}`)" v-if="isGroup == 1">
						<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/jielong.png" style="width:94rpx;"
							mode="widthFix"></image>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部输入栏 -->
		<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<view class="iphoneX flex items-center w-full">
				<!-- H5下不能录音，输入栏布局改动一下 -->
				<!-- #ifndef H5 -->
				<view class="voice">
					<view class="icon" :class="isVoice?'jianpan':'yuyin'" @tap="switchVoice"></view>
				</view>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<view class="more" @tap="showMore">
					<view class="icon add"></view>
				</view>
				<!-- #endif -->
				<view class="textbox">
					<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']"
						@touchstart="havePermission" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd"
						@touchcancel="voiceCancel">{{voiceTis}}</view>
					<view class="text-mode " :class="isVoice?'hidden':''">
						<view class="box" @click.stop="hideDrawer">
							<!-- #ifdef APP || H5 -->
							<kn-edit ref="contentEdit" v-model="textMsg" @bindfocus="textareaFocus" maxHeight="300rpx"
								@bindblur="bindblur" style="width: 100%;" :readOnly="knEditDisabled"
								@inputA="bindinput"></kn-edit>
							<!-- #endif -->
							<!-- #ifdef MP-WEIXIN -->
							<kn-edit ref="contentEdit" v-model="textMsg" @bindfocus="textareaFocus" maxHeight="300rpx"
								style="width: 100%;" :readOnly="knEditDisabled" height="70rpx" @bindblur="bindblur"></kn-edit>
							<!-- #endif -->
							<!-- <textarea auto-height="true" v-model="textMsg" @focus="textareaFocus"  /> -->
						</view>
						<view class="em" @tap="chooseEmoji">
							<view class="icon biaoqing"></view>
						</view>
					</view>
				</view>
				<!-- #ifndef H5 -->
				<view class="more" @tap="showMore">
					<view class="icon add"></view>
				</view>
				<!-- #endif -->
				<view class="send" :class="isVoice?'hidden':''" @touchend.prevent="sendText">
					<view class="btn" style="background: #37ACA4;">发送</view>
				</view>
			</view>
		</view>
		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''">
				<view class="icon luyin2"></view>
			</view>
			<view class="cancel" :class="willStop?'':'hidden'">
				<view class="icon chehui"></view>
			</view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>
		<!-- 红包领取弹窗 -->
		<u-popup :show="redPacketShow" bgColor="transparent" mode="center" :safeAreaInsetBottom="false">
			<view class=" flex flex-col items-center">
				<view class="redContent relative">
					<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/img_kai.png" class="image-144 red-open"
						mode="" @click="redConfirm"></image>
				</view>
				<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_quxiao.png" class="image-64 mt-36"
					mode="" @click="redPacketShow = false"></image>
			</view>
		</u-popup>

		<!-- 红包状态弹窗 -->
		<u-popup :show="redPacketStateShow" bgColor="transparent" mode="center" :safeAreaInsetBottom="false">
			<view class="flex flex-col items-center">
				<view class="redContent relative redStateContent flex flex-col items-center justify-between"
					style="color: #FFE9B8;">
					<view class="flex flex-col items-center">
						<view class="flex items-center">
							<image :src="redPacketStateInfo.avatar" mode="" class="image-64 round"></image>
							<view class="text-36 ml-16 font-700">
								{{redPacketStateInfo.nickName}}发的红包
							</view>
						</view>
						<view class="text-36 mt-48" v-if="redPacketStateInfo.state == 1">
							{{redPacketStateInfo.content}}
						</view>
						<view class="mt-48 font-700" style="font-size: 120rpx;" v-else>
							{{redPacketStateInfo.price}}
						</view>
					</view>

					<view class="flex items-center" style="color: #FFE9B8;"
						@click="$tab.nav(`/pages/chat2/groupRedPacketEnd?id=${redPacketId}`)" v-if="isGroup == 1">
						<view class="mr-12 text-32">
							查看领取详情
						</view>
						<u-icon name="arrow-right" color="#FFE9B8"></u-icon>
					</view>
				</view>
				<image src="http://api.fceos.cn/qiliaoyun/profile/appImages/icon_quxiao.png" class="image-64 mt-36"
					mode="" @click="redPacketStateShow = false"></image>
			</view>
		</u-popup>

		<videoPlay :previewVideoSrc="previewVideoSrc" @close="previewVideoSrc = ''"></videoPlay>

		<u-modal :show="permissionShow" title="权限说明" :content='permissionContent' confirmText="允许" cancelText="禁止"
			@confirm="permissionConfirm" @cancel="permissionShow = false" :showCancelButton="true"></u-modal>

	<div class="">
		<SelectGroupListUser ref="selectGroupListUser" :show="aSelectShow" @close="aSelectShow = false"
			@confirm="handleASelectConfirm" :isGroupLeader="isGroupLeader"></SelectGroupListUser>
	</div>
	</view>
</template>
<script>
	import {
		getToken
	} from "@/utils/auth.js"

	import {
		nanoid
	} from 'nanoid'

	import socket from 'plus-websocket'

	import knEdit from '@/components/lf-kn-editor/kn_editor.vue'

	// #ifdef APP
	const PPSHOOT = uni.requireNativePlugin('PP-SHOOT')

	const savePath = plus.io.convertLocalFileSystemURL('_doc/shoot/')

	const testModule = uni.requireNativePlugin('zx_album')

	const fileFun = uni.requireNativePlugin('GW-ChooseFileModule')

	import UniShare from 'uni_modules/uni-share/js_sdk/uni-share.js';
	const uniShare = new UniShare();
	// #endif

	import videoPlay from "@/components/videoPlay.vue"
import SelectGroupListUser from "@/components/SelectGroupListUser/SelectGroupListUser.vue"

	export default {
		onBackPress({
			from
		}) {
			console.log(from);
			if (from == 'backbutton') {
				this.$nextTick(function() {
					uniShare.hide()
				})
				return uniShare.isShow;
			}
		},
		components: {
			knEdit,
			videoPlay,
			SelectGroupListUser
		},
		data() {
			return {
				//文字消息
				textMsg: '',
				//消息列表
				isHistoryLoading: false,
				scrollAnimation: false,
				scrollToView: '',
				msgList: [],
				msgImgList: [],
				previewVideoSrc: "",
				permissionContent: "",
				permissionIndex: 0,
				scrollTop: "",

				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: "手指上滑 取消发送",
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				recordLength: 0,
				permissionShow: false,
				temPerData: null,

				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				// 抽屉参数
				popupLayerClass: '',
				// more参数
				hideMore: true,
				//表情定义
				hideEmoji: true,
				emojiList: [
					[{
						"url": "2.gif",
					}, {
						"url": "3.gif",
					}, {
						"url": "4.gif",
					}, {
						"url": "5.gif",
					}, {
						"url": "6.gif",
					}, {
						"url": "7.gif",
					}, {
						"url": "8.gif",
					}, {
						"url": "9.gif",
					}, {
						"url": "10.gif",
					}, {
						"url": "11.gif",
					}, {
						"url": "12.gif",
					}, {
						"url": "13.gif",
					}, {
						"url": "14.gif",
					}, {
						"url": "15.gif",
					}, {
						"url": "16.gif",
					}, {
						"url": "17.gif",
					}, {
						"url": "18.gif",
					}, {
						"url": "19.gif",
					}, {
						"url": "20.gif",
					}, {
						"url": "21.gif",
					}, {
						"url": "22.gif",
					}, {
						"url": "23.gif",
					}, {
						"url": "24.gif",
					}, {
						"url": "25.gif",
					}],
					[{
						"url": "26.gif",
					}, {
						"url": "27.gif",
					}, {
						"url": "28.gif",
					}, {
						"url": "29.gif",
					}, {
						"url": "30.gif",
					}, {
						"url": "31.gif",
					}, {
						"url": "32.gif",
					}, {
						"url": "33.gif",
					}, {
						"url": "34.gif",
					}, {
						"url": "35.gif",
					}, {
						"url": "36.gif",
					}, {
						"url": "37.gif",
					}, {
						"url": "38.gif",
					}, {
						"url": "39.gif",
					}, {
						"url": "40.gif",
					}, {
						"url": "41.gif",
					}, {
						"url": "42.gif",
					}, {
						"url": "43.gif",
					}, {
						"url": "44.gif",
					}, {
						"url": "45.gif",
					}, {
						"url": "46.gif",
					}, {
						"url": "47.gif",
					}, {
						"url": "48.gif",
					}, {
						"url": "49.gif",
					}],
					[{
						"url": "50.gif",
					}, {
						"url": "51.gif",
					}, {
						"url": "52.gif",
					}, {
						"url": "53.gif",
					}, {
						"url": "54.gif",
					}, {
						"url": "55.gif",
					}, {
						"url": "56.gif",
					}, {
						"url": "57.gif",
					}, {
						"url": "58.gif",
					}, {
						"url": "59.gif",
					}, {
						"url": "60.gif",
					}, {
						"url": "61.gif",
					}, {
						"url": "62.gif",
					}, {
						"url": "63.gif",
					}, {
						"url": "64.gif",
					}, {
						"url": "65.gif",
					}, {
						"url": "66.gif",
					}, {
						"url": "67.gif",
					}, {
						"url": "68.gif",
					}, {
						"url": "69.gif",
					}, {
						"url": "70.gif",
					}, {
						"url": "71.gif",
					}, {
						"url": "72.gif",
					}, {
						"url": "73.gif",
					}],
					[{
						"url": "74.gif",
					}, {
						"url": "75.gif",
					}, {
						"url": "76.gif",
					}, {
						"url": "77.gif",
					}, {
						"url": "78.gif",
					}, {
						"url": "79.gif",
					}, {
						"url": "80.gif",
					}, {
						"url": "81.gif",
					}, {
						"url": "82.gif",
					}, {
						"url": "83.gif",
					}, {
						"url": "84.gif",
					}, {
						"url": "85.gif",
					}, {
						"url": "86.gif",
					}, {
						"url": "87.gif",
					}, {
						"url": "88.gif",
					}, {
						"url": "89.gif",
					}, {
						"url": "90.gif",
					}, {
						"url": "91.gif",
					}, {
						"url": "92.gif",
					}, {
						"url": "93.gif",
					}, {
						"url": "94.gif",
					}, {
						"url": "95.gif",
					}, {
						"url": "96.gif",
					}, {
						"url": "97.gif",
					}],
					[{
						"url": "98.gif",
					}, {
						"url": "99.gif",
					}, {
						"url": "100.gif",
					}, {
						"url": "101.gif",
					}, {
						"url": "102.gif",
					}, {
						"url": "103.gif",
					}, {
						"url": "104.gif",
					}, {
						"url": "105.gif",
					}, {
						"url": "106.gif",
					}, {
						"url": "107.gif",
					}, {
						"url": "108.gif",
					}, {
						"url": "109.gif",
					}, {
						"url": "110.gif",
					}, {
						"url": "111.gif",
					}, {
						"url": "112.gif",
					}, {
						"url": "113.gif",
					}, {
						"url": "114.gif",
					}, {
						"url": "115.gif",
					}, {
						"url": "116.gif",
					}, {
						"url": "117.gif",
					}, {
						"url": "118.gif",
					}, {
						"url": "119.gif",
					}, {
						"url": "120.gif",
					}, {
						"url": "121.gif",
					}],
					[{
						"url": "122.gif",
					}, {
						"url": "123.gif",
					}, {
						"url": "124.gif",
					}, {
						"url": "125.gif",
					}, {
						"url": "126.gif",
					}, {
						"url": "127.gif",
					}, {
						"url": "128.gif",
					}, {
						"url": "129.gif",
					}, {
						"url": "130.gif",
					}, {
						"url": "131.gif",
					}, {
						"url": "132.gif",
					}, {
						"url": "133.gif",
					}, {
						"url": "134.gif",
					}, {
						"url": "135.gif",
					}, {
						"url": "136.gif",
					}, {
						"url": "137.gif",
					}, {
						"url": "138.gif",
					}, {
						"url": "139.gif",
					}, {
						"url": "140.gif",
					}, {
						"url": "141.gif",
					}, {
						"url": "142.gif",
					}, {
						"url": "143.gif",
					}, {
						"url": "144.gif",
					}, {
						"url": "145.gif",
					}],
					[{
							"url": "146.gif",
						},
						{
							"url": "147.gif",
						},
						{
							"url": "148.gif",
						},
						{
							"url": "149.gif",
						},
						{
							"url": "150.gif",
						},
						{
							"url": "151.gif",
						},
					]
				],

				globalData: getApp().globalData.config,

				groupId: "", //当前会话组id
				loading: false,
				pageNum: 1, //历史消息列表分页

				chatSocket: null,
				isSocket: false, //socket是否打开
				socketTimer: null, //socket发送心跳的计时器
				againSocketTimer: null, //重连socket

				userInfo: this.$store.getters.userInfo,

				isGroup: null,

				// 红包
				redPacketShow: false,
				redPacketId: null,

				title: null,

				id: null, //查详情id

				redPacketStateShow: false,
				redPacketStateInfo: {
					avatar: "",
					nickName: "",
					content: "",
					state: 1, //显示content
					price: null
				},

				msgScrolldeltaY: null,


				readOnly: false,
				groupNum: null,

				popId: null, //消息处理id
				withdraw: false,
				source: null,

				otherMpWeixin: "",

				keyboardHeight: 0, //键盘高度
				inputBoxHeight: 0,

				aSelectShow: false,
				atUserList: [],
				isGroupLeader: false,
				
				isMute:false,//群聊是否禁言
			};
		},
		computed: {
			phoneBH() {
				// #ifdef H5
				return 0
				// #endif

				// #ifndef H5
				return uni.getSystemInfoSync().safeAreaInsets.bottom
				// #endif
			},
			msgListBottom() {
				return this.inputBoxHeight + this.keyboardHeight + this.phoneBH
			},
			knEditDisabled(){
				if(this.isMute){
					return true
				}else{
					return this.readOnly
				}
				return
			}
		},
		onLoad(option) {
			// #ifdef MP-WEIXIN
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage']
			})
			// #endif

			this.onKeyboardHeightChange = ({
				height
			}) => {
				this.keyboardHeight = height
			}

			uni.onKeyboardHeightChange(this.onKeyboardHeightChange);

			this.groupId = option.groupId
			this.isGroup = option.isGroup
			this.title = option.title
			if (this.isGroup == 1) {
				this.id = option.groupId
				this.$nextTick(()=>{
					this.$refs.selectGroupListUser.getData(this.id)
				})
				this.otherMpWeixin = option.id
			} else {
				this.id = option.id
			}

			this.source = option.newUser
			
			// 获取历史消息
			this.getMsgList(option);

			this.isSocket = true

			//链接socket
			this.socketInit()

			//语音自然播放结束
			this.AUDIO.onEnded((res) => {
				this.playMsgid = null;
			});
			// #ifndef H5
			//录音开始事件
			this.RECORDER.onStart((e) => {
				this.recordBegin(e);
			})
			//录音结束事件
			this.RECORDER.onStop((e) => {
				this.recordEnd(e);
			})
			// #endif
		},
		async onShow() {
			uni.removeStorageSync('appLaunchedByPush')
			if (this.isGroup == 1) {
				const res = await this.$Api.chat.groupDetail(this.groupId)
				this.title = res.data.groupInfo.groupName + '(' + res.data.groupInfo.groupUserNum + ')'
				this.groupNum = res.data.groupInfo.groupUserNum

				this.isGroupLeader = res.data.groupInfo.groupLeaderId == this.userInfo.userId ? true : false
				
				if(res.data.groupInfo.isMute == 1){
					this.isMute = true
				}else{
					this.isMute = false
				}
			}

			uni.setNavigationBarColor({
				backgroundColor: '#FFF',
				frontColor: '#000000'
			})
		},
		onUnload() {
			this.isSocket = false
			// 页面卸载 关闭socket
			this.chatSocket.close()
			// 清除计时器
			clearInterval(this.socketTimer)
			clearInterval(this.keyboardTime)
		},
		onReady() {
			let view = uni.createSelectorQuery().in(this).select(".input-box");
			view
				.fields({
						size: true,
						scrollOffset: true,
					},
					(data) => {
						this.inputBoxHeight = data.height
					}
				)
				.exec();
		},
		methods: {
			handleASelectConfirm(e) {
				if (e.type == 1) {
					this.$refs.contentEdit.insertContent(e.data.nickName)
					this.atUserList.push({
						...e.data,
						text: `@${e.data.nickName}`
					})
				} else {
					this.atUserList = [...this.atUserList, ...e.data.map((item, index) => {
						if (index == 0) {
							this.$refs.contentEdit.insertContent(item.nickName)
						} else {
							this.$refs.contentEdit.insertContent(`@${item.nickName}`)
						}
						return {
							...item,
							text: `@${item.nickName}`
						}
					})]
				}
				this.aSelectShow = false
			},
			bindinput(e) {
				console.log(1)
				if(this.isGroup == 1){
					this.aSelectShow = true
				}
			},
			uniShare(row) {
				row.select = false
				//公共的分享参数配置  类型（type）、链接（herf）、标题（title）、summary（描述）、imageUrl（缩略图）
				let content = {
					type: row.msgContentType == 'text' ? 1 : 2,
					title: '富乐万家聊天内容分享',
				}
				if (row.msgContentType == 'img') {
					content.imageUrl = row.content.url
				} else {
					content.summary = row.content.text.replace(/<[^>]*>/g, '')
				}
				uniShare.show({
					content: content,
					menus: [{
							"img": "/static/app-plus/sharemenu/wechatfriend.png",
							"text": "微信好友",
							"share": { //当前项的分享参数配置。可覆盖公共的配置如下：分享到微信小程序，配置了type=5
								"provider": "weixin",
								"scene": "WXSceneSession"
							}
						},
						{
							"img": "/static/app-plus/sharemenu/wechatmoments.png",
							"text": "微信朋友圈",
							"share": {
								"provider": "weixin",
								"scene": "WXSceneTimeline"
							}
						}
					],
					cancelText: "取消分享",
				}, e => { //callback
					console.log(uniShare.isShow);
					console.log(e);
				})
			},
			handleForward() {
				this.$tab.nav(`/pages/chat2/forward?forwardId=${this.popId}`)
			},
			handleChooseFile(flag) {
				// #ifdef APP
				if (!flag) {
					if (plus.os.name == 'Android' && plus.navigator.checkPermission(
							'android.permission.READ_EXTERNAL_STORAGE') === 'undetermined') {
						this.permissionIndex = 3
						this.permissionContent =
							'富乐万家存储权限申请说明:便于您使用该功能在聊天场景中，选择相应文件发送给好友!'
						this.permissionShow = true
						return
					}
				}

				this.permissionShow = false

				fileFun.chooseFile({
					count: 5,
					extension: ['doc', 'xls', 'ppt', 'pdf', 'docx', 'pptx', 'xlsx'],
				}, (res) => {
					res.files.forEach(item => {
						this.$Api.common.uploadFile(`file://${item.path}`).then(upload => {
							let msg = {
								name: item.name,
								url: upload.url,
								size: `${(item.size / 1000).toFixed(1)}kb`
							};
							this.sendMsg(msg, 'file');
						})
					})
				})
				// #endif
				// #ifdef MP-WEIXIN
				wx.chooseMessageFile({
					count: 5,
					type: 'file',
					extension: ['doc', 'xls', 'ppt', 'pdf', 'docx', 'pptx', 'xlsx'],
					success: (res) => {
						console.log(res)
						res.tempFiles.forEach(item => {
							this.$Api.common.uploadFile(item.path).then(upload => {
								let msg = {
									name: item.name,
									url: upload.url,
									size: `${(item.size / 1000).toFixed(1)}kb`
								};
								this.sendMsg(msg, 'file');
							})
						})
					}
				})
				// #endif
			},
			handleReEdit(row) {
				let text = JSON.parse(row.remark)
				this.$refs.contentEdit.setContents(JSON.parse(text.content).text)
			},
			handleBack() {
				if (this.isGroup == 0) {
					this.$tab.back()
				} else {
					if (this.otherMpWeixin == "") {
						this.$tab.back()
					} else {
						this.$tab.reLaunch(`/pages/index/index`)
					}
				}
			},
			permissionConfirm() {
				if (this.permissionIndex == 0) {
					this.voiceBegin(this.temPerData)
				}
				if (this.permissionIndex == 1) {
					this.chooseImage(true)
				}
				if (this.permissionIndex == 2) {
					this.camera(true)
				}
				if (this.permissionIndex == 3) {
					this.handleChooseFile(true)
				}
			},
			closePop() {
				this.msgList.forEach(item => {
					item.select = false
				})
			},
			msgScroll(e) {
				this.msgScrolldeltaY = e.detail.deltaY
			},
			async handleWithdraw() {
				const res = await this.$Api.chat.rebackMsg({
					id: this.popId,
					groupId: this.groupId
				})
			},
			async handleDelete() {
				this.$modal.confirm('确认删除?').then(async con => {
					if (con) {
						const res = await this.$Api.chat.deleteMsg(this.popId)

						let findIndex = this.msgList.findIndex(item => {
							return item.id == this.popId
						})
						this.msgList.splice(findIndex, 1)
					}
				})
			},
			handleCopy() {
				let findIndex = this.msgList.findIndex(item => {
					return item.id == this.popId
				})
				let text = this.msgList[findIndex].content.text
				var matches = text.replace(/<[^>]*>/g, '');

				uni.setClipboardData({
					data: matches,
					success: () => {
						this.msgList.forEach(item => {
							item.select = false
						})
						this.$modal.msg('内容已复制!')
					}
				});
			},
			handlePopup(row) {
				if (row.sendUserInfo.userId == this.$store.getters.userInfo.userId) {
					// 获取当前时间
					var now = new Date();

					// 创建一个表示2分钟的时间间隔
					var twoMinutesAgo = new Date(now.getTime() - 2 * 60000); // 2分钟 = 2 * 60 * 1000 毫秒

					// 将时间字符串转换为Date对象
					var dateTime = new Date(row.createTime);

					// 判断当前时间是否超过2分钟
					if (dateTime < twoMinutesAgo) {
						this.withdraw = false
					} else {
						this.withdraw = true
					}
				} else {
					this.withdraw = false
				}

				this.msgList.forEach(item => {
					item.select = false
				})
				row.select = true
				this.popId = row.id


			},
			async hendClick(item) {
				const res = await this.$Api.chat.usersIsFriend({
					userId1: item.senderId
				})
				if (res.data) {
					this.$tab.nav(`/pages/chat2/userDetail?userId=${item.senderId}`)
				} else {
					this.$tab.nav(`/pages/chat2/addFriend?userName=${item.sendUserInfo.userId}`)
				}
			},
			rightClick() {
				if (this.isGroup == 1) {
					this.$tab.nav(`/pages/chat2/groupChatDetail?id=${this.id}`)
				} else {
					this.$tab.nav(`/pages/chat2/userDetail?userId=${this.id}`)
				}
			},
			socketInit() {
				let that = this
				// #ifdef MP-WEIXIN
				this.chatSocket = uni.connectSocket({
					url: `${this.globalData.chatWs}?token=${getToken()}&groupId=${this.groupId}`,
					complete: () => {}
				});
				// #endif

				// #ifndef MP-WEIXIN
				this.chatSocket = socket.connectSocket({
					url: `${this.globalData.chatWs}?token=${getToken()}&groupId=${this.groupId}`,
					complete: () => {}
				});
				// #endif

				this.chatSocket.onOpen(function(res) {
					console.log('聊天连接已打开！');

					that.socketTimer = setInterval(() => {
						that.chatSocket.send({
							data: 'ping'
						})
					}, 10000)

					if (that.againSocketTimer) {
						clearInterval(that.againSocketTimer)
						that.againSocketTimer = null
					}

					that.screenMsg()
				});

				this.chatSocket.onError(function(res) {
					console.log('WebSocket连接打开失败，请检查！', res);
					setTimeout(() => {
						that.socketInit()
					}, 10000)
				});

				this.chatSocket.onClose(function(res) {
					if (that.isSocket) {
						clearInterval(that.socketTimer)
						that.againSocketTimer = setInterval(() => {
							that.socketInit()
						}, 5000)
					}
					console.log('WebSocket 已关闭！', res);
				});
			},
			// 接受消息(筛选处理)
			screenMsg() {
				this.chatSocket.onMessage((msg) => {
					console.log('socket收', msg)
					// 判断消息不是心跳
					if (msg.data != 'pong') {
						let data = JSON.parse(msg.data)
						if (data.msgType == 1) {
							try {
								data.content = JSON.parse(data.content)
							} catch (e) {
								//TODO handle the exception
							}
						}
						if (data.msgType == 0) {
							// 系统消息
							switch (data.msgContentType) {
								case 'text':
								case 'sysTime':
									this.addSystemTextMsg(data);
									break
								case 'msg_reback':
									let id = JSON.parse(data.remark).msgId
									let findIndex = this.msgList.findIndex(item => {
										return item.id == id
									})
									this.msgList.splice(findIndex, 1)
									this.addSystemTextMsg(data);
									break;
								case 'redEnvelope':
									this.addSystemRedEnvelopeMsg(data);
									break;
							}
						} else if (data.msgType == 1) {
							// 用户消息
							switch (data.msgContentType) {
								case 'text':
									this.addTextMsg(data);
									break;
								case 'atText':
									this.addTextMsg(data);
									break;
								case 'voice':
									this.addVoiceMsg(data);
									break;
								case 'img':
									this.addImgMsg(data);
									break;
								case 'video':
									this.addVideoMsg(data);
									break;
								case 'red_packet':
									this.addRedEnvelopeMsg(data);
									break;
								case 'file':
									this.addVoiceMsg(data);
									break;
								case 'jielong':
									this.addVoiceMsg(data);
									break;
							}
							//非自己的消息震动
							if (data.senderId != this.userInfo.userId) {
								console.log('振动');
								uni.vibrateLong();
							}
						}
						this.$nextTick(function() {
							if (this.msgScrolldeltaY >= -200 || this.msgScrolldeltaY == NaN || data
								.senderId == this.userInfo.userId) {
								// 滚动到底
								this.scrollToView = 'msg' + data.id
							} else {
								// 下边有多少未读
							}
						});
					}
				})
			},

			//触发滑动到顶部(加载历史信息记录)
			async loadHistory(e) {
				if (this.isHistoryLoading) {
					return;
				}
				this.isHistoryLoading = true; //参数作为进入请求标识，防止重复请求
				this.scrollAnimation = false; //关闭滑动动画
				let Viewid = this.msgList[0].id; //记住第一个信息ID
				console.log('Viewid', Viewid)
				// 调接口拿到历史聊天记录
				const msgList = await this.$Api.chat.msgList({
					pageNum: this.pageNum,
					pageSize: 30,
					groupId: this.groupId
				})

				// 处理消息
				this.msgList = [
					...msgList.rows.map(item => {
						// 先处理格式转换
						if (item.msgType == 1) {
							try {
								item.content = JSON.parse(item.content)
								item.content.text = item.content.text.replace(/<img/g,
									'<img style="width:20px;height:20px;vertical-align: middle;"');

								item.content.text = item.content.text.replace(/<p/g,
									'<p style="display: flex;align-items: center;flex-wrap: wrap;"');
							} catch (e) {
								//TODO handle the exception
							}
						}
						// 判断如果是用户消息并且是图片消息 处理图片显示大小
						if (item.msgType == 1 && item.msgContentType == 'img') {
							item.content = this.setPicSize(item.content)
							this.msgImgList.unshift(item.content.url);
						}

						if (item.msgType == 1 && item.msgContentType == 'video') {
							item.content = this.setPicSize(item.content)
						}
						return item
					}).reverse(),
					...this.msgList
				]
				console.log('this.msgList[0].id', this.msgList[0].id)


				//这段代码很重要，不然每次加载历史数据都会跳到顶部
				this.$nextTick(function() {
					this.scrollToView = 'msg' + Viewid; //跳转上次的第一行信息位置
					this.$nextTick(function() {
						this.scrollAnimation = true; //恢复滚动动画
					});
				});

				this.loading = false
				if (msgList.total > this.msgList.length) {
					this.pageNum++
					this.isHistoryLoading = false;
				} else {
					this.isHistoryLoading = true;
				}
			},
			// 加载初始页面消息
			async getMsgList(option) {
				let form
				if (option && option.msgId) {
					form = {
						pageSize: 20,
						groupId: this.groupId,
						msgId:option.msgId
					}
				} else {
					form = {
						pageNum: this.pageNum,
						pageSize: 20,
						groupId: this.groupId
					}
				}

				// 调接口拿到历史聊天记录
				const msgList = await this.$Api.chat.msgList(form)

				console.log('历史聊天记录', msgList)
				this.msgList = msgList.rows.map(item => {
					// 先处理格式转换
					if (item.msgType == 1) {
						try {
							item.content = JSON.parse(item.content)
						} catch (e) {
							//TODO handle the exception
						}
					}

					if (item.msgType == 1 && (item.msgContentType == 'text' || item.msgContentType == 'atText')) {
						try {
							item.content.text = item.content.text.replace(/\n/g, "<br />");

							item.content.text = item.content.text.replace(/<img/g,
								'<img style="width:20px;height:20px;vertical-align: middle;"');

							item.content.text = item.content.text.replace(/<p/g,
								'<p style="display: flex;align-items: center;flex-wrap: wrap;"');
						} catch (e) {
							//TODO handle the exception
						}
					}

					// 判断如果是用户消息并且是图片消息 处理图片显示大小
					if (item.msgType == 1 && item.msgContentType == 'img') {
						item.content = this.setPicSize(item.content)
						this.msgImgList.unshift(item.content.url);
					}

					if (item.msgType == 1 && item.msgContentType == 'video') {
						item.content = this.setPicSize(item.content)
					}
					return item
				}).reverse()

				this.loading = false
				if (msgList.total > this.msgList.length) {
					this.pageNum++
					this.isHistoryLoading = false;
				} else {
					this.isHistoryLoading = true;
				}

				// 滚动到底部
				setTimeout(() => {
					this.$nextTick(() => {
						if(option.msgId){
							this.scrollToView = 'msg' + this.msgList[0].id;
						}else{
							this.scrollToView = 'msg' + this.msgList[this.msgList.length - 1].id;
						}
						
						this.$nextTick(() => {
							this.scrollAnimation = true;
						});
					});
				}, 300)
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(content) {
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
				let maxH = uni.upx2px(350); //350是定义消息图片最大高度
				if (content.w > maxW || content.h > maxH) {
					let scale = content.w / content.h;
					content.w = scale > 1 ? maxW : maxH * scale;
					content.h = scale > 1 ? maxW / scale : maxH;
				}
				return content;
			},
			//更多功能(点击+弹出) 
			showMore() {
				this.isVoice = false;
				this.hideEmoji = true;
				this.readOnly = true
				if (this.hideMore) {
					this.hideMore = false;
					this.openDrawer();
					this.textareaFocus()
				} else {
					this.hideDrawer();
				}
			},
			// 打开抽屉
			openDrawer() {
				this.popupLayerClass = 'showLayer';
			},
			// 隐藏抽屉
			hideDrawer(e) {
				this.popupLayerClass = '';
				this.readOnly = false
				setTimeout(() => {
					this.hideMore = true;
					this.hideEmoji = true;
				}, 150);
			},
			// 选择图片发送
			chooseImage(flag) {
				// #ifdef APP
				if (!flag) {
					if (plus.os.name == 'Android' && plus.navigator.checkPermission(
							'android.permission.READ_EXTERNAL_STORAGE') === 'undetermined') {
						this.permissionIndex = 1
						this.permissionContent =
							'富乐万家对照片/视频/音频权限申请说明:便于您使用该功能上传您的照片/图片/视频及用于更换头像,发送聊天图片,发送聊天视频,发送动态等场景中读取内容'
						this.permissionShow = true
						return
					}
				}
				// #endif
				this.permissionShow = false

				// #ifdef APP
				testModule.invoke({}, (res) => {
					res.forEach(item => {
						item = JSON.parse(item)
						if (item.format == 'video') {
							uni.showLoading({
								title: "视频上传中..."
							})
							uni.getImageInfo({
								src: item.coverLocalPath,
								success: (image) => {
									this.$Api.common.uploadFile(item.coverLocalPath).then(
										imgUpload => {
											this.$Api.common.uploadFile(item.localPath)
												.then(
													videoUpload => {
														let msg = {
															poster: imgUpload.url,
															url: videoUpload.url,
															w: image.width,
															h: image.height,
															duration: this
																.formatSecondsToHHMMSS(
																	item.second)
														};
														this.sendMsg(msg, 'video');
														uni.hideLoading()
														this.hideDrawer(true)
													})
										})

								}
							});
						} else {
							uni.getImageInfo({
								src: item.localPath,
								success: (image) => {
									console.log('item.localPath',item.localPath)
									console.log('image',image)
									this.$Api.common.uploadFile(item.localPath).then(
										upload => {
											console.log('upload.url',upload.url)
											let msg = {
												url: upload.url,
												w: image.width,
												h: image.height
											};
											this.sendMsg(msg, 'img');
											this.hideDrawer(true)
										})
								}
							});
						}
					})
				})
				// #endif

				// #ifdef MP-WEIXIN
				this.getImage('album');
				// #endif
			},
			//拍照发送
			camera(flag) {
				// #ifdef APP
				if (!flag) {
					if (plus.os.name == 'Android' && plus.navigator.checkPermission('android.permission.CAMERA') ===
						'undetermined' || plus.navigator.checkPermission('android.permission.RECORD_AUDIO') ===
						'undetermined') {
						this.permissionIndex = 2
						this.permissionContent =
							'富乐万家对照片/视频/音频/摄像头权限申请说明:便于您使用该功能上传您的照片/图片/视频及用于更换头像,发送聊天图片,发送聊天视频,发送动态等场景中读取和写入内容'
						this.permissionShow = true
						return
					}
				}

				this.permissionShow = false

				PPSHOOT.start({
						androidSize: 600, //android录制分辨率（考虑到设备型号众多，给出一个视频高度，自动适配这个宽度高度的最接近的分辨率）
						iOSSize: 2, //ios录制分辨率因为就固定的几种，传入需要类型即可 352x288 = 0, 640x480 = 1,1280x720 = 2,1920x1080 = 3,4K3840x2160 = 4,
						maxDuration: 15, //录制最长时间
						type: 1, //1拍照+录象 2拍照 3录象
						savePath: savePath, //视频存储目录
						begin_record_time: 500 //设置按住多久开始录像 默认500毫米
					},
					res => {
						console.log('结果', res.data)

						if (res.data.type == 'photo') {
							uni.getImageInfo({
								src: res.data.path,
								success: (image) => {
									this.$Api.common.uploadFile(res.data.path).then(
										upload => {
											let msg = {
												url: upload.url,
												w: image.width,
												h: image.height
											};
											this.sendMsg(msg, 'img');
										})
								}
							});
						} else {
							uni.showLoading({
								title: "视频上传中..."
							})
							uni.getImageInfo({
								src: res.data.thumbnail,
								success: (image) => {
									this.$Api.common.uploadFile(res.data.thumbnail).then(imgUpload => {
										this.$Api.common.uploadFile(res.data.path).then(
											videoUpload => {
												let msg = {
													poster: imgUpload.url,
													url: videoUpload.url,
													w: image.width,
													h: image.height,
													duration: `00:${res.data.duration > 9 ? res.data.duration : '0' + res.data.duration}`
												};
												this.sendMsg(msg, 'video');
												uni.hideLoading()
												this.hideDrawer(true)
											})
									})

								}
							});
						}

						//可返回照片或录像地址及封面

					}
				)
				// #endif

				// #ifdef MP-WEIXIN
				this.getImage('camera');
				// #endif
			},
			formatSecondsToHHMMSS(seconds) {
				// 计算小时
				const hours = Math.floor(seconds / 3600);
				// 计算分钟
				const minutes = Math.floor((seconds % 3600) / 60);
				// 计算秒数
				const secs = seconds % 3600 % 60;

				// 格式化为两位数
				const formattedHours = String(hours).padStart(2, '0');
				const formattedMinutes = String(minutes).padStart(2, '0');
				const formattedSeconds = String(secs).padStart(2, '0');

				return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
			},
			//发红包
			handRedEnvelopes() {
				if (!this.$store.getters.userInfo.payPassword) {
					this.$modal.confirm('还未设置支付密码，是否设置?').then(con => {
						if (con) {
							this.$tab.nav(`/pages/forgetPassword?type=0`)
						}
					})
				} else {
					this.$tab.redTo(
						`/pages/chat2/sendRedPacket?isGroup=${this.isGroup}&groupId=${this.groupId}&title=${this.title}&groupNum=${this.groupNum}`
					)
				}
			},
			//选照片 or 拍照
			getImage(type) {
				this.hideDrawer(true);
				uni.chooseImage({
					sourceType: [type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						console.log(res.tempFilePaths)

						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image) => {
									console.log(image.width);
									console.log(image.height);
									this.$Api.common.uploadFile(res.tempFilePaths[i]).then(
										upload => {
											let msg = {
												url: upload.url,
												w: image.width,
												h: image.height
											};
											this.sendMsg(msg, 'img');
										})

								}
							});
						}
					}
				});
			},
			openFile(row) {
				uni.showLoading({
					title: '下载中...'
				})
				uni.downloadFile({
					url: row.url,
					success: function(res) {
						uni.hideLoading()
						// #ifdef APP
						// 拿到临时文件的绝对路径
						let filepathss = plus.io.convertLocalFileSystemURL(res.tempFilePath);
						// 通过这个路径来拿到他
						plus.io.resolveLocalFileSystemURL(filepathss, function(entry) {
							const tempFileName = entry.name;
							entry.getParent(function(parentDicEntry) {
								console.log(parentDicEntry.fullPath)
								entry.moveTo({
									fullPath: parentDicEntry.fullPath + '/'
								}, row.name, function(newFile) {
									uni.openDocument({
										fileType: 'xlsx',
										filePath: newFile.fullPath,
										success: function(res2) {
											console.log('打开文档成功');
										},
										fail: function(err) {
											if (err.errCode == 1 || err
												.code == 1) {
												uni.showToast({
													title: `未找到能该类型文件的手机应用`,
													icon: 'none'
												})
											}
											console.log(err)
										}
									});
								}, function(moveError) {
									uni.showToast({
										title: `已在第三方应用中打开过，请在第三方应用查看时保存`,
										icon: 'none'
									})
								})
							})
						})
						// #endif
						// #ifdef MP-WEIXIN
						uni.openDocument({
							filePath: res.tempFilePath,
							showMenu: true,
							success: function(res) {
								console.log('打开文档成功');
							},
							fail: (err) => {

							}
						});
						// #endif
					}
				});
			},
			// 选择表情
			chooseEmoji() {
				this.hideMore = true;
				this.readOnly = true
				if (this.hideEmoji) {
					this.hideEmoji = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			//添加表情
			addEmoji(em) {
				let tem = 'http://api.fceos.cn/qiliaoyun/profile/appImages/emoji/' + em.url
				this.$refs.contentEdit.insertImage(tem)
			},
			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus() {
				this.scrollToView = ""
				setTimeout(() => {
					this.scrollToView = 'msg' + this.msgList[this.msgList.length - 1].id;
				}, 300)
			},
			bindblur() {

			},
			// 发送文字消息
			sendText() {
				setTimeout(() => {
					let text = this.textMsg.replace('<p><br></p>', '').replace(
						'<p style="text-align: left;"><br></p>', '')
					if (!text || text == "") {
						return;
					}
					// #ifdef APP || H5
					let msg = {
						text: this.textMsg
					}
					// #endif

					// #ifdef MP-WEIXIN
					// atText
					let msg = {
						text: this.textMsg.replace(/\<br>/g, ''),
					}
					// #endif

					if (this.atUserList.length > 0) {
						let toUserIds = this.atUserList.filter(item => {
							return this.textMsg.indexOf(item.text) != -1
						}).map(item => {
							return item.userId
						})

						if (toUserIds.length > 0) {
							this.sendMsg(msg, 'atText', toUserIds);
						} else {
							this.sendMsg(msg, 'text');
						}
					}else{
						this.sendMsg(msg, 'text');
					}

					this.$refs.contentEdit.clearContent()
					this.popupLayerClass = '';
				}, 300)
			},
			// 发送消息
			sendMsg(content, type, toUserIds) {
				let msg = {
					msgType: 1,
					msgContentType: type,
					content: content
				}
				if (type == "atText") {
					msg.toUserIds = toUserIds
				}
				if (this.againSocketTimer == null) {
					console.log(msg)
					this.chatSocket.send({
						data: JSON.stringify(msg)
					})
				} else {
					msg.senderId = this.userInfo.userId
					msg.socket = 0
					msg.sendUserInfo = this.userInfo
					msg.id = nanoid()
					this.addTextMsg(msg)
					this.socketInit()
					this.$nextTick(function() {
						// 滚动到底
						this.scrollToView = 'msg' + msg.id
					});
				}
			},
			// 发送失败的消息重发
			retransmission(row) {
				this.$modal.confirm('消息发送失败，重新发送?').then(con => {
					if (con) {
						this.sendMsg({
							text: row.content.text
						}, 'text')
						if (this.isSocket) {
							let index = this.msgList.findIndex(item => {
								return row.id == item.id
							})
							this.msgList.splice(index, 1)
						}
					}
				})
			},
			// 添加文字消息到列表
			addTextMsg(msg) {
				try {
					msg.content.text = msg.content.text.replace(/\n/g, "<br />");
					msg.content.text = msg.content.text.replace(/<img/g,
						'<img style="width:20px;height:20px;vertical-align: middle;"');
				} catch (e) {
					//TODO handle the exception
				}
				msg.content.text = msg.content.text.replace(/<p/g,
					'<p style="display: flex;align-items: center;flex-wrap: wrap;"');
				this.msgList.push(msg);
			},
			// 添加语音消息到列表
			addVoiceMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg) {
				msg.content = this.setPicSize(msg.content);
				this.msgImgList.push(msg.content.url);
				this.msgList.push(msg);
			},
			// 添加视频消息到列表
			addVideoMsg(msg) {
				msg.content = this.setPicSize(msg.content);
				this.msgList.push(msg);
			},
			addRedEnvelopeMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加系统红包消息到列表
			addSystemRedEnvelopeMsg(msg) {
				this.msgList.push(msg);
			},
			// 打开红包
			async openRedEnvelope(item) {
				this.redPacketId = item.content.id
				// 查红包状态
				const res = await this.$Api.chat.redPacketInfo({
					redPacketId: item.content.id
				})
				console.log('红包详情', res)

				this.redPacketStateInfo.avatar = item.sendUserInfo.avatar
				this.redPacketStateInfo.nickName = item.sendUserInfo.nickName

				if (res.isReceive == 1) {
					if (this.isGroup == 1) {
						this.$tab.nav(`/pages/chat2/groupRedPacketEnd?id=${this.redPacketId}`)
					} else {
						this.$tab.nav(`/pages/chat2/redPacketEnd?id=${this.redPacketId}`)
					}
				} else if (res.isReceive == 0) {
					if (res.redPacketInfo.state == 2) {
						this.redPacketStateInfo.content = "红包已过期!"
						this.redPacketStateInfo.state = 1
						this.redPacketStateShow = true
					} else if (res.redPacketInfo.state == 0) {
						this.redPacketStateInfo.content = "红包已领完!"
						this.redPacketStateInfo.state = 1
						this.redPacketStateShow = true
					} else if (res.redPacketInfo.state == 1) {
						this.redPacketShow = true
					}
				}
			},
			// 预览图片
			showPic(msg) {
				console.log(msg, this.msgImgList)
				uni.previewImage({
					indicator: "none",
					current: msg.content.url,
					urls: this.msgImgList
				});
			},
			// 预览视频
			showVideo(video) {
				this.previewVideoSrc = video
			},
			// 播放语音
			playVoice(msg) {
				this.playMsgid = msg.id;
				this.AUDIO.src = msg.content.url;
				this.$nextTick(function() {
					this.AUDIO.play();
				});
			},
			havePermission(e) {
				// #ifdef APP
				if (plus.os.name == 'Android' && plus.navigator.checkPermission(
						'android.permission.RECORD_AUDIO') === 'undetermined') {
					this.permissionIndex = 0
					this.permissionContent = '富乐万家对麦克风权限申请说明:便于您使用该功能发送语音消息场景'
					this.temPerData = e
					this.permissionShow = true
					return
				}
				// #endif
				this.voiceBegin(e)
			},
			// 录音开始
			voiceBegin(e) {
				if (e.touches.length > 1) {
					return;
				}
				this.permissionShow = false
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: "mp3"
				}); //录音开始,
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000)
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop(); //录音结束
			},
			//录音结束(回调文件)
			recordEnd(e) {
				clearInterval(this.recordTimer);
				if (!this.willStop) {
					console.log("e: " + JSON.stringify(e));
					this.$Api.common.uploadFile(e.tempFilePath).then(res => {
						console.log('音频上传', res)
						let msg = {
							length: 0,
							url: res.url
						}
						let min = parseInt(this.recordLength / 60);
						let sec = this.recordLength % 60;
						min = min < 10 ? '0' + min : min;
						sec = sec < 10 ? '0' + sec : sec;
						msg.length = min + ':' + sec;
						this.sendMsg(msg, 'voice');
					})
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
			},
			// 切换语音/文字输入
			switchVoice() {
				this.hideDrawer(true);
				this.isVoice = this.isVoice ? false : true;
			},
			discard() {
				return;
			},
			async redConfirm() {
				this.redPacketShow = false
				if (this.isGroup == 1) {
					this.$tab.nav(`/pages/chat2/groupRedPacketEnd?id=${this.redPacketId}`)
				} else {
					this.$tab.nav(`/pages/chat2/redPacketEnd?id=${this.redPacketId}`)
				}
			},
		}
	}
</script>
<style lang="scss">
	@import "@/static/HM-chat/css/style.scss";

	.redContent {
		width: 620rpx;
		height: 920rpx;
		background: url('http://api.fceos.cn/qiliaoyun/profile/appImages/img_dailingqu.png') no-repeat;
		background-size: 100% 100%;
	}

	.redStateContent {
		background: url('http://api.fceos.cn/qiliaoyun/profile/appImages/img_hongbao.png') no-repeat;
		background-size: 100% 100%;
		padding: 180rpx 0 60rpx 0;
	}

	.red-open {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 84rpx;
	}

	/deep/ .ql-editor p {
		font-size: 36rpx;
	}

	/deep/ .ql-editor {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.play-btn {
		width: 60rpx;
		height: 60rpx;
		position: absolute;
		left: calc(50% - 30rpx);
		top: calc(50% - 30rpx);
	}

	.duration {
		position: absolute;
		right: 12rpx;
		bottom: 12rpx;
		color: #FFF;
		font-size: 16rpx;
	}

	.file-box {
		background-color: #FFF !important;
		width: 60%;
		color: #000;
	}

	.jielong {
		padding: 4rpx 12rpx;
	}
</style>